#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
#include <functional>

#include "log.hpp"
#include "protocol.hpp"

enum
{
    USAGE_ERR = 1,
    SOCKET_ERR,
    CONNECT_ERR
};

class CalClient
{
public:
    CalClient(const std::string &serverip, const uint16_t &serverport)
        : _sock(-1), _serverip(serverip), _serverport(serverport) {}

    void initClient()
    {

        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(FATAL, "client socket create error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "client socket create success");
    }

    void start()
    {
        // 填充服务器端的IP和端口号
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        // 建立连接
        if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
        {
            logMessage(FATAL, "socket connect error");
            exit(CONNECT_ERR);
        }
        logMessage(NORMAL, "socket connect success");

        std::string line;
        std::string inbuffer;
        std::cout << "输入的示例: x+y" << std::endl;
        while (true)
        {
            // 发送请求
            std::cout << "Enter# ";
            std::getline(std::cin, line);

            // 构建一个结构化的请求
            Request req = ParseLine(line);
            // 将请求进行序列化
            std::string content;
            req.serialize(&content);

            // 添加上报头并发送
            std::string send_str = enLength(content);
            std::cout << "sendstring: \n"
                      << send_str << std::endl;
            send(_sock, send_str.c_str(), send_str.size(), 0);

            // 接收响应
            // package用来存储一个完整的报文，text用来存储正文
            std::string package, text;
            if (!recvPackage(_sock, inbuffer, &package))
                continue;
            if (!deLength(package, &text))
                continue;

            Response resp;
            resp.deserialize(text);
            std::cout << "exitCode: " << resp._exitcode << std::endl;
            std::cout << "result: " << resp._result << std::endl;
        }
    }

    // 对输入的内容进行拆分
    Request ParseLine(const std::string &line)
    {
        int status = 0; // 0: 操作符之前，1: 碰到操作符 2: 操作符之后
        int i = 0;
        int cnt = line.size();

        std::string left, right;
        char op;
        while (i < cnt)
        {
            switch (status)
            {
            case 0:
            {
                if (!isdigit(line[i]))
                {
                    op = line[i];
                    status = 1;
                }
                else
                    left.push_back(line[i++]);
            }
            break;
            case 1:
                i++;
                status = 2;
                break;
            case 2:
                right.push_back(line[i++]);
                break;
            }
        }

        int x = std::stoi(left);
        int y = std::stoi(right);
        std::cout << x << " " << y << " " << op << std::endl;
        return Request(x, y, op);
    }

    ~CalClient()
    {
        close(_sock);
    }

private:
    int _sock;
    std::string _serverip;
    uint16_t _serverport;
};